document.addEventListener('DOMContentLoaded', function() {
    // 获取书签并显示在表格中
    chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
        let bookmarkBody = document.getElementById('bookmarkBody');
        bookmarkBody.innerHTML = ''; // 清空表格
        collectBookmarkData(bookmarkTreeNodes, bookmarkBody, '');
    });

    // 添加导出 CSV 的功能
    document.getElementById('exportCSVBtn').addEventListener('click', exportBookmarksAsCSV);
});

// 递归遍历书签树，收集书签数据并显示在表格中
function collectBookmarkData(bookmarks, tableBody, parentFolder) {
    for (let bookmark of bookmarks) {
        // 更新当前的文件夹路径
        let currentFolder = parentFolder;
        if (bookmark.title && !bookmark.url) {
            // 这是一个文件夹，更新路径
            currentFolder = parentFolder ? parentFolder + '/' + bookmark.title : bookmark.title;
        }

        if (bookmark.url) {
            let row = tableBody.insertRow();
            let titleCell = row.insertCell(0);
            let urlCell = row.insertCell(1);
            let folderCell = row.insertCell(2);
            let dateCell = row.insertCell(3);

            titleCell.textContent = bookmark.title || '';
            urlCell.innerHTML = `<a href="${bookmark.url}" target="_blank">${bookmark.url}</a>`;
            folderCell.textContent = currentFolder || '';
            dateCell.textContent = bookmark.dateAdded ? new Date(bookmark.dateAdded).toLocaleString() : '';
        }

        if (bookmark.children) {
            collectBookmarkData(bookmark.children, tableBody, currentFolder);
        }
    }
}

// 导出书签为 CSV 文件的函数
function exportBookmarksAsCSV() {
    chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
        let rows = [];
        // 添加 CSV 的表头
        rows.push(['标题', 'URL', '文件夹路径', '添加日期'].join(','));
        collectBookmarkDataForCSV(bookmarkTreeNodes, rows, '');
        let csvContent = rows.join('\n');
        let blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        let url = URL.createObjectURL(blob);
        let link = document.createElement('a');
        let currentDate = new Date().toISOString().slice(0,10);
        link.download = `Bookmarks_${currentDate}.csv`;
        link.href = url;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}

// 递归遍历书签树，收集书签数据用于 CSV 导出
function collectBookmarkDataForCSV(bookmarks, rows, parentFolder) {
    for (let bookmark of bookmarks) {
        // 更新当前的文件夹路径
        let currentFolder = parentFolder;
        if (bookmark.title && !bookmark.url) {
            // 这是一个文件夹，更新路径
            currentFolder = parentFolder ? parentFolder + '/' + bookmark.title : bookmark.title;
        }

        if (bookmark.url) {
            let title = '"' + (bookmark.title.replace(/"/g, '""') || '') + '"';
            let url = '"' + bookmark.url.replace(/"/g, '""') + '"';
            let dateAdded = bookmark.dateAdded ? new Date(bookmark.dateAdded).toLocaleString() : '';
            let folderPath = '"' + (currentFolder.replace(/"/g, '""') || '') + '"';
            let row = [title, url, folderPath, dateAdded].join(',');
            rows.push(row);
        }

        if (bookmark.children) {
            collectBookmarkDataForCSV(bookmark.children, rows, currentFolder);
        }
    }
}
